// pages/operation/classRecord/evaluateStudent/index.js
import { ClassModel } from "../../../../api/api-work/classModel.js"
import { config } from "../../../../utils/config.js";
import Toast from '@vant/weapp/toast/toast';
const classModel = new ClassModel()

// 录音实例
const recorderManager = wx.getRecorderManager();
// 播放实例
const innerAudioContext = wx.createInnerAudioContext();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    query: {},
    templateOptions: [],
    showTemplate: false,
    templateId: "",
    templateName: "请选择模板",
    templateList: [],
    contentList: [],
    fileList: [],
    description: "",
    showRecorder: false,
    recorderStatus: "1", // 未录音
    recorderTime: "00:00",
    minutes: 0,
    seconds: 0,
    timer: null,
    audioTempfile: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const param = JSON.parse(options.param)
    this.setData({
      query: param
    })
    console.log("评价学员：", this.data.query)
    this.getTemplateList();

    // 监听录音事件， 开始录音
    recorderManager.onStart(() => {
      console.log('recorder start');
    });
    // 结束录音
    recorderManager.onStop((res) => {
      console.log('recorder stop', res);
      const { tempFilePath } = res;
      // tempFilePath 是录音文件的临时路径，可以用来播放或上传
      this.setData({
        audioTempfile: tempFilePath
      })
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  // 获取评分模板
  getTemplateList() {
    classModel.getTemplateListApi({ pageNum: 1, pageSize: 999, state: 1 }).then(res => {
      if (res.rows && res.rows.length > 0) {
        this.setData({
          templateOptions: res.rows,
          templateName: res.rows[0].name,
          templateId: res.rows[0].id
        })
        this.getTempById()
      }
    })
  },
  showTemplateTap() {
    this.setData({
      showTemplate: true
    })
  },
  chooseTemplateSelect(e) {
    const rows = e.detail;
    this.setData({
      templateName: rows[0].name,
      templateId: rows[0].id
    })
    this.getTempById()
  },
  getTempById() {
    classModel.getTempByIdApi({ id: this.data.templateId }).then(res => {
      let arr = res[0].tName;
      arr.forEach(item => {
        item["score"] = 5;
        item["lId"] = item.id;
      })
      this.setData({
        templateList: arr
      })
    })
  },
  onChangeStar(e) {
    let arr = this.data.templateList;
    arr.forEach(item => {
      if (item.id == e.currentTarget.dataset.query.id) {
        item.score = e.detail
      }
    })
    this.setData({
      templateList: arr
    })
  },
  // 选择照片
  chooseImage() {
    let _this = this;
    wx.chooseMedia({
      count: 9,
      mediaType: ['image'],
      success(res) {
        const tempFilePaths = res.tempFiles;
        let arr = [];
        tempFilePaths.forEach(item => {
          arr.push(item.tempFilePath)
        })
        const successUp = 0;
        const failUp = 0;
        const count = 0;// 第几张
        const length = tempFilePaths.length; // 总数
        _this.recursionUpLoading(arr, 'image', successUp, failUp, count, length)
      }
    })
  },
  recursionUpLoading(filePaths, fileType, successUp, failUp, count, length) {
    console.log("递归中：", filePaths, successUp, failUp, count, length)
    let _this = this;
    wx.uploadFile({
      url: `${config.api_base_url}/wx/obsStorage/upload`,
      filePath: filePaths[count],
      header: { 'Authorization': 'Bearer ' + wx.getStorageSync("token"), },
      name: 'file',
      success: (e) => {
        const result = JSON.parse(e.data);
        let list = _this.data.fileList;
        list.push({
          type: fileType,
          url: result.data[0]
        })
        this.setData({
          fileList: list
        })
        successUp++
      },
      fail: (e) => {
        failUp++
      },
      complete: (e) => {
        count++; // 下一张
        if (count == length) {
          Toast(`上传成功`);
        } else {
          // 递归调用，上传下一张
          _this.recursionUpLoading(filePaths, fileType, successUp, failUp, count, length)
        }
      }
    })
  },
  lookBigImage(e) {
    wx.previewImage({
      urls: [e.currentTarget.dataset.query.url],
    })
  },
  // 选择视频
  chooseVideo() {
    let _this = this;
    wx.chooseMedia({
      count: 5,
      mediaType: ['video'],
      success(res) {
        const tempFilePaths = res.tempFiles;
        let arr = [];
        tempFilePaths.forEach(item => {
          arr.push(item.tempFilePath)
        })
        const successUp = 0;
        const failUp = 0;
        const count = 0;// 第几张
        const length = tempFilePaths.length; // 总数
        _this.recursionUpLoading(arr, 'video', successUp, failUp, count, length)
      }
    })
  },
  // 录音
  chooseRecorder() {
    this.setData({
      showRecorder: true
    })
  },
  // 开始录音
  startRecorder() {
    this.setData({
      recorderStatus: "2", // 录音中
    })
    if (this.timer) {
      clearInterval(this.timer)
    }
    this.timer = setInterval(() => {
      this.data.seconds += 1
      if (this.data.seconds == 60) {
        // clearInterval(this.timer)
        this.setData({
          seconds: 0,
          minutes: this.data.minutes + 1
        })
        // return;
      }
      if (this.data.minutes == 3) {
        clearInterval(this.timer)
        return;
      }
      this.setData({
        recorderTime: `${this.toZero(this.data.minutes)}:${this.toZero(this.data.seconds)}`
      })
    }, 1000)

    const options = {
      duration: 180000, // 最长录音时间，单位毫秒
      sampleRate: 44100, // 采样率
      numberOfChannels: 1, // 录音通道数
      encodeBitRate: 192000, // 编码比特率
      format: 'mp3' // 音频格式，有效值 aac/mp3
    };
    // 开始录音
    recorderManager.start(options);
  },
  // 录音完成
  stopRecorder() {
    this.setData({
      recorderStatus: "3", // 录音完成
    })
    if (this.timer) {
      clearInterval(this.timer)
    }
    // 停止录音
    recorderManager.stop();
  },
  // 播放录音
  playRecorder() {
    this.setData({
      recorderStatus: "4", // 播放录音
    })
    innerAudioContext.src = this.data.audioTempfile; // 设置音频文件路径
    innerAudioContext.play();
  },
  // 添0 
  toZero(timeNumber) {
    return timeNumber < 10 ? '0' + timeNumber : timeNumber
  },
  // 取消录音
  cancelRecorder() {
    this.setData({
      recorderStatus: "1",
    })
  },
  // 完成录音
  completeRecorder() {
    console.log("完成录音： ", this.data.audioTempfile)
    const _this = this;
    wx.uploadFile({
      url: `${config.api_base_url}/wx/obsStorage/upload`,
      filePath: this.data.audioTempfile,
      header: { 'Authorization': 'Bearer ' + wx.getStorageSync("token"), },
      name: 'file',
      success: (e) => {
        const result = JSON.parse(e.data);
        let list = _this.data.fileList;
        list.push({
          type: "radio",
          url: result.data[0]
        })
        this.setData({
          fileList: list,
          showRecorder: false,
          recorderTime: "00:00",
        })
      }
    })
  },
  deleteFile(e) {
    const index = e.currentTarget.dataset.query;
    classModel.deleteFileApi([this.data.fileList[index].url]).then(res => {
      let arr = this.data.fileList;
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
      this.setData({
        fileList: arr
      })
    })
  },
  completeEvaluate() {
    let urls = []
    this.data.fileList.forEach(item => {
      urls.push(item.url)
    })
    const obj = {
      description: this.data.description,
      state: "0",
      tEvaluateScores: this.data.templateList,
      url: urls,
      ids: [this.data.query]
    }
    classModel.updateEvaluateApi(obj).then(res => {
      console.log("评价成功！")
      wx.navigateBack()
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})